#pragma GCC optimize("O3")

#include "DMADrawer.h"
#include "PayBox.h"
#include "TCPReceiver.h"
#include <ArduinoOTA.h>
#include <TFT_eSPI.h>
#include <esp_wifi.h>

TFT_eSPI tft;
TCPReceiver recv;
uint32_t count = 0;
uint32_t bright = 20;

void setup(void) {
  Serial.begin(115200);
  payTFTInit(tft, 16);
  tft.println("Wifi Screen Projection");
  autoConfigWifi();
  ArduinoOTA.begin();
  tft.println(WiFi.localIP().toString());
  payLEDInit();
  delay(2000);
  setup_t s;
  tft.getSetup(s);
  int f = SPI_FREQUENCY;
  recv.setup(s.r0_x_offset, s.r0_y_offset, 320, 240, f, TFT_MOSI, TFT_MISO,
             TFT_SCLK, TFT_CS, TFT_DC);

  bindKeyEvent(PAY_KEY_ON, [] { ESP.restart(); });

  bindKeyEvent(PAY_KEY_ADD, [] {
    bright += 20;
    payTFTBrightness(bright);
  });

  bindKeyEvent(PAY_KEY_MINUS, [] {
    if (bright >= 20) {
      bright -= 20;
      payTFTBrightness(bright);
    }
  });
}

void loop(void) {
  ArduinoOTA.handle();
  recv.loop();
  count++;
  if (count > 100) {
    count = 0;
    auto led = random(0x010101, 0xffffff);
    payLEDShow(led);
  }
}
